<template>
  <div>
    <!-- <el-drawer title="店铺" :visible.sync="drawer" size="40%">
      <el-table
        :data="brandChannelShopList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="品牌" align="center" prop="brand" />
        <el-table-column label="渠道" align="center" prop="channel" />
        <el-table-column label="店铺名称" align="center" prop="shopName" />
      </el-table>
      <div class="footer" style="margin-top: 100px; text-align: center">
        <el-button size="small" type="primary" plain @click="handleSave"
          >保存配置</el-button
        >
      </div>
    </el-drawer> -->
    <el-form :model="form" ref="performanceForm" label-width="100px">
      <el-row>
        <h3>1、店铺</h3>
        <el-form-item label="">
          <span v-if="tosubmit">{{ value.join("-") }}</span>
          <el-cascader
            v-if="!tosubmit"
            class="cascader-limited-scroll"
            v-model="value"
            placeholder="已选择店铺"
            :options="cascadeList"
            :props="{ checkStrictly: true }"
            style="width: 300px; height: 30px"
          />
        </el-form-item>
        <el-form-item label="">
          <el-select
            :disabled="tosubmit"
            v-model="saleModel"
            placeholder="销售模式"
            clearable
            filterable
            allow-create
          >
            <el-option
              v-for="dict in contractTypeList"
              :key="dict"
              :label="dict"
              :value="dict"
            />
          </el-select>
        </el-form-item>
      </el-row>
      <el-row>
        <h3>2、业绩目标(年份)</h3>
        <el-row>
          <el-form-item label="">
            <el-date-picker
              :disabled="tosubmit"
              type="year"
              v-model="oneYear"
              placeholder="当前年份"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="">
            <el-input-number v-model="targetAll"></el-input-number>
            <el-button type="primary" @click="handletargetAll"
              >批量填充</el-button
            >
          </el-form-item>
        </el-row>

        <el-col :span="5">
          <el-card>
            <div slot="header">
              <span>第一季度: {{ quarters[0].total }}（w）</span>
            </div>
            <el-form-item
              v-for="(month, index) in form.months.slice(0, 3)"
              :key="index"
              :label="`${index + 1}月（w）`"
            >
              <el-input-number
                style="width: 150px"
                v-model="month.target"
                :min="0"
                @change="calculateQuartersAndYear"
              ></el-input-number>
              <el-button
                style="margin-left: 5px"
                size="mini"
                @click="handleyearMonth(month)"
                >配置</el-button
              >
            </el-form-item>
          </el-card>
        </el-col>
        <el-col :span="1" class="center">
          <span>➕</span>
        </el-col>
        <el-col :span="5">
          <el-card>
            <div slot="header">
              <span>第二季度: {{ quarters[1].total }}（w）</span>
            </div>
            <el-form-item
              v-for="(month, index) in form.months.slice(3, 6)"
              :key="index"
              :label="`${index + 4}月（w）`"
            >
              <el-input-number
                style="width: 150px"
                v-model="month.target"
                :min="0"
                @change="calculateQuartersAndYear"
              ></el-input-number>
              <el-button
                style="margin-left: 5px"
                size="mini"
                @click="handleyearMonth(month)"
                >配置</el-button
              >
            </el-form-item>
          </el-card>
        </el-col>
        <el-col :span="1" class="center"> ➕ </el-col>
        <el-col :span="5">
          <el-card>
            <div slot="header">
              <span>第三季度: {{ quarters[2].total }}（w）</span>
            </div>
            <el-form-item
              v-for="(month, index) in form.months.slice(6, 9)"
              :key="index"
              :label="`${index + 7}月（w）`"
            >
              <el-input-number
                style="width: 150px"
                v-model="month.target"
                :min="0"
                @change="calculateQuartersAndYear"
              ></el-input-number>
              <el-button
                style="margin-left: 5px"
                size="mini"
                @click="handleyearMonth(month)"
                >配置</el-button
              >
            </el-form-item>
          </el-card>
        </el-col>
        <el-col :span="1" class="center"> ➕ </el-col>
        <el-col :span="5">
          <el-card>
            <div slot="header">
              <span>第四季度: {{ quarters[3].total }}（w）</span>
            </div>
            <el-form-item
              v-for="(month, index) in form.months.slice(9, 12)"
              :key="index"
              :label="`${index + 10}月（w）`"
            >
              <el-input-number
                style="width: 150px"
                v-model="month.target"
                :min="0"
                @change="calculateQuartersAndYear"
              ></el-input-number>
              <el-button
                style="margin-left: 5px"
                size="mini"
                @click="handleyearMonth(month)"
                >配置</el-button
              >
            </el-form-item>
          </el-card>
        </el-col>
      </el-row>
      <!-- 月份业绩目标设置 -->
      <!-- <el-form-item
      v-for="(month, index) in form.months"
      :key="index"
      :label="`${index + 1}月（元）`"
    >
      <el-input-number
        v-model="month.target"
        :min="0"
        @change="calculateQuartersAndYear"
      ></el-input-number>
    </el-form-item> -->

      <!-- 季度业绩目标显示 -->
      <!-- <div>
      
      <div v-for="(quarter, index) in quarters" :key="index">
        <span>第{{ index + 1 }}季度: {{ quarter.total }}</span>
      </div>
    </div>
    -->

      <!-- 业绩目标一年总和 -->
      <!-- <el-form-item label="单个员工全年业绩目标(2024年)">
        <span>{{ totalYear }}</span>
      </el-form-item> -->

      <el-row :gutter="20" class="m-t-5px">
        <el-col :span="6" :lg="4" :md="12" :sm="12" :xs="24">
          <el-card class="rounded-md dark:bg-black" shadow="hover">
            <div class="flex justify-between">
              <span class="card-panel-text">3、全年业绩目标</span>
              <!-- <el-tag
            :type="
              index == 0
                ? 'primary'
                : index == 1
                ? 'success'
                : index == 2
                ? 'warning'
                : 'danger'
            "
            >{{ item.unit }}</el-tag
          > -->
            </div>
            <div class="text-2xl">
              <span class="card-panel-num">{{ totalYear }}万</span>
            </div>
            <!-- <el-divider
              direction="horizontal"
              content-position="left"
            ></el-divider>
            <div class="flex justify-between">
              <span class="text">环比</span>
              <span
                ><span class="text">{{
                  itemData.fractionDefective + "%"
                }}</span></span
              >
            </div> -->
          </el-card>
        </el-col>
      </el-row>
      <!-- <h3>3、全年业绩目标:{{ totalYear }}(w)</h3> -->
      <!-- 提交按钮 -->
      <!-- <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </el-form-item> -->
    </el-form>
    <div
      slot="footer"
      class="dialog-footer"
      style="margin-top: 50px; text-align: center"
    >
      <el-button type="primary" @click="submitForm">提交</el-button>
      <el-button @click="cancel">取 消</el-button>
      <!-- <el-button @click="addDomain">新增</el-button> -->
    </div>

    <el-dialog
      :visible.sync="openInfo"
      width="1000px"
      append-to-body
      v-if="openInfo"
    >
      <div class="el-dialog-div">
        <component :is="'yearMonth'" :row="row"></component>
      </div>
    </el-dialog>
  </div>
</template>  
  
<script>
import moment from "moment";
import {
  listBiSaleTarget,
  getBiSaleTarget,
  delBiSaleTarget,
  addBiSaleTarget,
  updateBiSaleTarget,
  importData,
  selectUpdateData,
} from "@/api/sale/BiSaleTarget";
import { listBrandChannelShop, listAll } from "@/api/chart/brandChannelShop";
import yearMonth from "./yearMonth.vue";
export default {
  name: "BiSaleTargetEdit",
  components: { yearMonth },
  data() {
    return {
      row: {},
      openInfo: false,
      saleModel: "自营",
      contractTypeList: ["自营", "合作"],
      tosubmit: false,
      oneYear: moment(new Date()).format("YYYY"),
      cascadeList: [],
      value: [],
      shopList: [],
      list: [],
      brandChannelShopList: [],
      targetAll: "",
      drawer: false,
      form: {
        months: Array.from({ length: 12 }, (_, i) => ({ target: 0 })), // 初始化12个月的业绩目标为0
      },
      quarters: [], // 存储季度业绩目标的数组
      totalYear: 0, // 业绩目标一年总和
    };
  },
  watch: {
    // 监听form.months的变化来重新计算季度和年总和
    "form.months": {
      handler() {
        this.calculateQuartersAndYear();
      },
      deep: true, // 深度监听
    },
  },
  created() {
    //     shopId: 15546829
    // shopName: vfu运动outlet店
    // targetAmount: 12
    // dataYear: 2024
    if (this.$route.query.row) {
      const id = {
        shopId: this.$route.query.row.shopId,
        dataYear: this.$route.query.row.dataYear,
        saleModel: this.$route.query.row.saleModel,
      };
      console.log(JSON.stringify(id));
      selectUpdateData(id).then((response) => {
        console.log(JSON.stringify(response));
        this.tosubmit = true;
        this.value = response.salesGrade;
        this.saleModel = response.saleModel;
        this.oneYear = JSON.stringify(response.dataYear);
        let list = [];
        response.monthlySaleTarget.forEach((item) => {
          list.push({ target: item.targetAmount, yearMonth: item.yearMonth });
        });
        this.form.months = list;
      });
    } else {
      this.getdataSourceList();
    }
  },

  mounted() {
    // 初始化时也可以计算一次季度和年总和（如果必要的话）
    this.calculateQuartersAndYear();
  },
  methods: {
    handleyearMonth(month) {
      this.row = { ...month, shopId: this.$route.query.row.shopId };
      this.openInfo = true;
    },

    cancel() {
      this.$router.go(-1);
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.list = selection.map((item) => item);
    },
    handleSave() {
      this.shopList = [];
      this.list.forEach((item) => {
        this.shopList.push(item.shopName);
      });
      this.drawer = false;
    },
    handletargetAll() {
      console.log(JSON.stringify(this.form.months));
      this.form.months.forEach((item) => {
        item.target = this.targetAll;
      });
      console.log(JSON.stringify(this.form.months));
      // this.calculateQuartersAndYear();
    },
    // 计算季度和年总和
    calculateQuartersAndYear() {
      // 重置季度数组和年总和
      this.quarters = Array.from({ length: 4 }, () => ({ total: 0 }));
      this.totalYear = 0;

      // 计算每个季度的总和
      for (let i = 0; i < this.form.months.length; i++) {
        const monthIndex = Math.floor(i / 3); // 计算月份对应的季度索引
        this.quarters[monthIndex].total += this.form.months[i].target;
        this.totalYear += this.form.months[i].target; // 累加月份到年总和
      }
    },
    // 提交表单
    submitForm() {
      console.log(this.oneYear);
      // return;
      // 在这里添加保存逻辑，比如发送请求到服务器
      console.log("提交业绩目标:", this.form);
      console.log(JSON.stringify(this.form));
      let list = [];

      for (let i = 0; i < this.form.months.length; i++) {
        if (i < 3) {
          list.push({
            dataSeason: 1,
            dataMonth: i + 1,
            targetAmount: this.form.months[i].target,
          });
        } else if (i < 6) {
          list.push({
            dataSeason: 2,
            dataMonth: i + 1,
            targetAmount: this.form.months[i].target,
          });
        } else if (i < 9) {
          list.push({
            dataSeason: 3,
            dataMonth: i + 1,
            targetAmount: this.form.months[i].target,
          });
        } else {
          list.push({
            dataSeason: 4,
            dataMonth: i + 1,
            targetAmount: this.form.months[i].target,
          });
        }
      }
      console.log(JSON.stringify(list));
      updateBiSaleTarget({
        salesGrade: this.value,
        saleModel: this.saleModel,
        dataYear: moment(this.oneYear).format("YYYY"),
        monthlySaleTarget: list,
      }).then((response) => {
        this.$modal.msgSuccess("提交成功");
        this.handleGo("/sale/BiSaleTarget");
      });
    },
    handleGo(path) {
      this.$router.push(path);
    },
    /** 查询品牌渠道店铺关系列表 */
    getdataSourceList() {
      listAll().then((response) => {
        // this.brandChannelShopList = response;
        let result = this.transformData(response);
        this.cascadeList = result;
        this.value = [
          result[0].label,
          result[0].children[0].label,
          result[0].children[0].children[0].label,
        ];
      });
    },
    //店铺渠道品牌转换

    transformData(data) {
      let result = [];

      data.forEach((item) => {
        let brand = item.brand;
        let channel = item.channel;
        let shopName = item.shopName;

        // 如果brand在结果数组中不存在，则创建一个新的数组
        let brandIndex = result.findIndex(
          (brandObj) => brandObj.label === brand
        );
        if (brandIndex === -1) {
          result.push({
            label: brand,
            value: brand,
            children: [],
            disabled: true,
          });
          brandIndex = result.length - 1;
        }

        // 如果channel在当前brand的children数组中不存在，则创建一个新的数组
        let channelIndex = result[brandIndex].children.findIndex(
          (channelObj) => channelObj.label === channel
        );
        if (channelIndex === -1) {
          result[brandIndex].children.push({
            label: channel,
            value: channel,
            children: [],
            disabled: true,
          });
          channelIndex = result[brandIndex].children.length - 1;
        }

        // 如果shopName在当前channel的children数组中不存在，则创建一个新的数组
        let shopIndex = result[brandIndex].children[
          channelIndex
        ].children.findIndex((shopObj) => shopObj.label === shopName);
        if (shopIndex === -1) {
          result[brandIndex].children[channelIndex].children.push({
            label: shopName,
            value: shopName,
            // children: []
          });
        }
      });

      return result;
    },
  },
};
</script>  
  
<style lang="scss" scoped>
/* 在这里添加你的样式 */
.center {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 260px;
}
.flex {
  display: flex;
  justify-content: space-between;
}
.card-panel-text {
  line-height: 18px;
  // color: rgba(0, 0, 0, 0.45);
  font-size: 20px;
  margin-bottom: 12px;
}

.card-panel-num {
  font-size: 20px;
  font-weight: 600;
}
</style>